﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace DG.Common.Extensions
{
}
namespace DG.Common.Mail
{
    
    public static class MailHelpers
    {
        public static bool SendEmailFromDengineToAdmin(string assunto, string corpoDoEmail, IEnumerable<KeyValuePair<Stream, string>> anexos = null)
        {
            var remetente = new MailAddress("error@dg.com", "DG - Error Monitor");
            var destinatarios = new[]
                {
                    new MailAddress("gedomingos@gmail.com", "George"),
                    new MailAddress("diogo.souza747@gmail.com", "Diogo Viado")
                };

            var credenciais = new NetworkCredential("klausporff", "novagilza1");
            return SendEmail("smtp.gmail.com", 587, credenciais, remetente, destinatarios, assunto, corpoDoEmail,
                             isSecure: true, anexos: anexos);
        }

        public static bool SendEmail(string smtpServer, int smtpPort, NetworkCredential credenciais, MailAddress remetente, MailAddress destinatario, string assunto, string mensagem, bool isSecure = false)
        {
            return SendEmail(smtpServer, smtpPort, credenciais, remetente, new[] { destinatario }, assunto, mensagem, isSecure);
        }

        public static bool SendEmail(string smtpServer, int smtpPort, ICredentialsByHost credenciais, MailAddress remetente,
                                     IEnumerable<MailAddress> destinatarios, string assunto, string mensagem, bool isSecure = false,
                                     IEnumerable<KeyValuePair<Stream, string>> anexos = null)
        {

            var smtpClient = new SmtpClient(smtpServer, smtpPort);


            var mailMessage = new MailMessage { From = remetente };
            foreach (var destinatario in destinatarios)
            {
                mailMessage.To.Add(destinatario);
            }

            mailMessage.Body = mensagem;
            mailMessage.Subject = assunto;

            if (anexos != null)
            {
                foreach (var anexo in anexos)
                {
                    anexo.Key.Position = 0;
                    mailMessage.Attachments.Add(new Attachment(anexo.Key, anexo.Value));
                }
            }

            smtpClient.EnableSsl = isSecure;

            smtpClient.Credentials = credenciais;

            smtpClient.Send(mailMessage);

            return true;
        }
    }
}
